// UI渲染模块
import { showToast } from './utils.js';
import dragAndDrop from './dragAndDrop.js';

// 跨标签页移动图标的通用函数
function moveIconBetweenTabs(srcData, targetTab) {
    
    // 验证数据完整性
    if (!window.data?.icons?.[srcData.tab] || !window.data?.icons?.[targetTab]) {
        console.error('标签页不存在:', srcData.tab, targetTab);
        return false;
    }
    
    const srcIndex = parseInt(srcData.index);
    const sourceIcons = window.data.icons[srcData.tab];
    
    // 验证索引有效性
    if (isNaN(srcIndex) || srcIndex < 0 || srcIndex >= sourceIcons.length) {
        console.error('索引无效:', { srcIndex, length: sourceIcons.length });
        return false;
    }
    
    const iconToMove = sourceIcons[srcIndex];
    if (!iconToMove) {
        console.error('图标不存在');
        return false;
    }
    
    // 检查重复URL
    const isDuplicate = window.data.icons[targetTab].some(icon => icon.url === iconToMove.url);
    if (isDuplicate) {
        window.showToast?.(`目标标签页"${targetTab}"已包含此URL`);
        return false;
    }
    
    // 执行移动操作
    sourceIcons.splice(srcIndex, 1);
    window.data.icons[targetTab].push(iconToMove);
    
    // 保存数据
    const saveResult = window.dataManager?.saveData?.(window.data);
    if (saveResult) {
        window.showToast?.(`已移动图标到"${targetTab}"`);
        return true;
    } else {
        console.error('数据保存失败');
        window.showToast?.('保存失败');
        return false;
    }
}

// 将函数暴露到全局作用域
window.moveIconBetweenTabs = moveIconBetweenTabs;

// 渲染标签页
export function renderTabs(data, currentTab) {
    const container = document.querySelector('.tab-scroll');
    if (!container) {
        console.error('Tab container not found');
        return;
    }
    
    // 清空容器
    container.innerHTML = '';
    
    // 手动创建默认标签页，确保至少有基本标签页
    if (!data.tabs || data.tabs.length === 0) {
        data.tabs = ['ALL', '首页'];
        data.icons = { 'ALL': [], '首页': [] };
        currentTab = '首页';
    }
    
    // 使用DocumentFragment一次性渲染所有标签
    const fragment = document.createDocumentFragment();
    
    // 渲染每个标签
    data.tabs.forEach(tab => {
        const tabBtn = document.createElement('div');
        tabBtn.className = 'tab-btn px-4 py-2 rounded-full cursor-pointer flex items-center whitespace-nowrap';
        tabBtn.dataset.tab = tab;
        
        // 设置样式
        if (tab === currentTab) {
            tabBtn.classList.add('bg-blue-500', 'text-white', 'hover:bg-blue-600');
        } else {
            tabBtn.classList.add('bg-gray-200', 'hover:bg-gray-300');
        }
        
        tabBtn.innerHTML = `
            <span class="tab-name">${tab}</span>
        `;
        
        // 添加点击事件
        tabBtn.addEventListener('click', () => {
            // 通过全局函数更新currentTab并重新渲染
            if (typeof window.switchTab === 'function') {
                window.switchTab(tab);
            }
        });
        
        // 添加拖拽事件监听器
        tabBtn.addEventListener('dragover', (e) => {
            e.preventDefault();
            e.dataTransfer.dropEffect = 'move';
            // 添加拖拽悬停效果
            if (tab !== window.currentTab) {
                tabBtn.classList.add('drop-hover');
            }
        });
        
        tabBtn.addEventListener('dragleave', (e) => {
            // 移除拖拽悬停效果
            tabBtn.classList.remove('drop-hover');
        });
        
        tabBtn.addEventListener('drop', (e) => {
            e.preventDefault();
            e.stopPropagation();
            
            // 移除拖拽悬停效果
            tabBtn.classList.remove('drop-hover');
            
            // 如果拖拽到当前标签页，不处理
            if (tab === window.currentTab) {
                return;
            }
            
            // 获取拖拽数据
            let srcData;
            try {
                srcData = JSON.parse(e.dataTransfer.getData('text/plain'));
            } catch (error) {
                console.error('无法解析拖拽数据:', error);
                return;
            }
            
            // 处理拖拽到标签页的逻辑
            if (!srcData || srcData.index === undefined) {
                console.error('拖拽数据无效');
                return;
            }
            
            // 切换到目标标签页
            window.currentTab = tab;
            
            // 执行跨标签页移动
            const success = moveIconBetweenTabs(srcData, tab);
            if (success && typeof window.renderAll === 'function') {
                window.renderAll();
            }
        });
        
        fragment.appendChild(tabBtn);
    });
    
    // 一次性添加到DOM
    container.appendChild(fragment);
    
    // 触发tabsRendered事件
    if (window.dispatchTabsRenderedEvent) {
        window.dispatchTabsRenderedEvent();
    }
}

// 渲染图标
export function renderIcons(data, currentTab) {
    const container = document.getElementById('icon-container');
    if (!container) return;
    
    container.innerHTML = '';
    
    let iconsToRender = [];
    
    // 特殊处理ALL页面
    if (currentTab === 'ALL') {
        for (const tab in data.icons) {
            if (tab !== 'ALL' && Array.isArray(data.icons[tab])) {
                const taggedIcons = data.icons[tab].map((icon, originalIndex) => ({
                    ...icon,
                    sourceTab: tab,
                    originalIndex
                }));
                iconsToRender = iconsToRender.concat(taggedIcons);
            }
        }
    } else {
        if (!Array.isArray(data.icons[currentTab])) {
            data.icons[currentTab] = [];
        }
        iconsToRender = data.icons[currentTab];
    }
    

    
    // 使用DocumentFragment批量处理DOM
    const fragment = document.createDocumentFragment();
    
    // 渲染所有图标
    iconsToRender.forEach((icon, index) => {
        const iconDiv = document.createElement('div');
        iconDiv.className = 'draggable relative p-3 cursor-pointer has-tooltip flex flex-col items-center justify-center transition-all hover:opacity-80';
        iconDiv.draggable = true;
        iconDiv.dataset.index = index;
        // 添加源标签页信息（用于ALL页面）
        if (icon.sourceTab) {
            iconDiv.dataset.sourceTab = icon.sourceTab;
        }
        
        // 安全地处理可能不完整的图标数据
        const name = icon.name || '未命名';
        const cover = icon.cover || '➕';
        const url = icon.url || '#';
        const description = icon.description || '';
        
        // 获取图标背景色（如果不存在则生成并保存）
        let gradient = icon.bgGradient;
        if (!gradient) {
            // 生成随机渐变背景色
            const gradients = [
                'linear-gradient(135deg, #6366f1, #8b5cf6)', // 紫色
                'linear-gradient(135deg, #3b82f6, #60a5fa)', // 蓝色
                'linear-gradient(135deg, #10b981, #34d399)', // 绿色
                'linear-gradient(135deg, #f59e0b, #fbbf24)', // 黄色
                'linear-gradient(135deg, #ef4444, #f87171)', // 红色
                'linear-gradient(135deg, #ec4899, #f472b6)', // 粉色
                'linear-gradient(135deg, #8b5cf6, #a78bfa)', // 紫罗兰
                'linear-gradient(135deg, #06b6d4, #22d3ee)', // 青色
            ];
            const seed = icon.name && icon.url ? 
                (icon.name + icon.url).split('').reduce((a, b) => ((a << 5) - a + b.charCodeAt(0)) | 0, 0) : 
                index;
            const gradientIndex = Math.abs(seed) % gradients.length;
            gradient = gradients[gradientIndex];
        }
        
        const iconHTML = `
            <div class="text-center w-full">
                ${icon.customImage ? 
                    `<div class="app-icon relative" style="background: transparent;">
                        <img src="${icon.customImage}" class="custom-image-preview" alt="${name}">
                    </div>` :
                    `<div class="app-icon" style="background: ${gradient}">
                        <span class="select-none">${cover}</span>
                    </div>`
                }
                <div class="text-xs font-medium truncate w-full text-center">${name}</div>
            </div>
            ${description ? `<div class="tooltip mt-2 bg-black text-white text-xs p-2 rounded bottom-full left-1/2 transform -translate-x-1/2 w-max max-w-xs">${description}</div>` : ''}
        `;
        
        iconDiv.innerHTML = iconHTML;
        
        // 点击跳转
        iconDiv.addEventListener('click', (e) => {
            if (!e.target.closest('.edit-btn') && !iconDiv.classList.contains('dragging')) {
                try {
                    window.open(url, '_blank');
                } catch (error) {
                    console.error('打开链接失败:', error);
                    showToast('打开链接失败，请检查URL');
                }
            }
        });
        
        iconDiv.addEventListener('contextmenu', function(e) {
            e.preventDefault();
            document.querySelectorAll('.context-menu').forEach(menu => menu.style.display = 'none');
            
            const contextMenu = document.getElementById('icon-context-menu');
            contextMenu.style.left = e.pageX + 'px';
            contextMenu.style.top = e.pageY + 'px';
            contextMenu.style.display = 'block';
            
            window.currentIcon = {
                element: this,
                index: parseInt(this.dataset.index),
                sourceTab: this.dataset.sourceTab || window.currentTab,
                tab: window.currentTab
            };
            return false;
        });
        
        fragment.appendChild(iconDiv);
    });
    
    // 添加系统设置图标（仅在ALL和首页标签页显示）
    if (currentTab === 'ALL' || currentTab === '首页') {
        const settingsIconDiv = document.createElement('div');
        settingsIconDiv.className = 'relative p-3 cursor-pointer flex flex-col items-center justify-center hover:opacity-80';
        settingsIconDiv.innerHTML = `
            <div class="text-center w-full">
                <div class="app-icon" style="background: linear-gradient(135deg, #6366f1, #8b5cf6)">
                    <span class="select-none">⚙️</span>
                </div>
                <div class="text-xs font-medium">系统设置</div>
            </div>
        `;
        
        settingsIconDiv.addEventListener('click', () => {
            const settingsModal = document.getElementById('settings-modal');
            if (settingsModal) {
                settingsModal.classList.remove('hidden');
            }
        });
        
        fragment.appendChild(settingsIconDiv);
    }
    
    // 添加"新增"图标（不在ALL页显示）
    if (currentTab !== 'ALL') {
        const addIconDiv = document.createElement('div');
        addIconDiv.className = 'draggable relative p-3 cursor-pointer flex flex-col items-center justify-center hover:opacity-80';
        addIconDiv.innerHTML = `
            <div class="text-center w-full">
                <div class="app-icon" style="background: linear-gradient(135deg, #d1d5db, #9ca3af)">
                    <span class="select-none">➕</span>
                </div>
                <div class="text-xs font-medium">添加导航</div>
            </div>
        `;
        
        addIconDiv.addEventListener('click', () => {
            // 需要访问main.js中的openModal函数
            if (typeof window.openModal === 'function') {
                window.openModal();
            }
        });
        
        fragment.appendChild(addIconDiv);
    }
    
    // 一次性添加所有元素到DOM
    container.appendChild(fragment);
    
    // 添加拖拽事件处理
    setTimeout(() => {
        if (typeof dragAndDrop.setupDragAndDrop === 'function') {
            dragAndDrop.setupDragAndDrop();
        }
    }, 0);
}